﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using TableProto;

public class ModuleAssetManager : Singleton<ModuleAssetManager> {

    private const string DownloadingKeys = "ModuleAssetManager.DownloadingKeys";

	private Dictionary<int, ModuleAssetState> ModuleAsset = new Dictionary<int, ModuleAssetState> ();

    private Dictionary<int, bool> versionCheck = new Dictionary<int, bool>();

	public const string ResName = "ResInfo.txt";

	private Action<string> UnzipDoneHander;

    private Queue<int> downloadQue = new Queue<int>();


	public override void Init ()
	{
		base.Init ();


        EventBus.Instance.AddEventHandler<int, long> (EventID.MODULE_UNZIP_DONE, this.UnzipDone);
        EventBus.Instance.AddEventHandler<int>(EventID.MODULE_DOWNLOAD_ERROR, this.DownError);
    }

	public override void UnInit ()
	{
		base.UnInit ();
		EventBus.Instance.RemoveEventHandler<int, long> (EventID.MODULE_UNZIP_DONE, this.UnzipDone);
        EventBus.Instance.RemoveEventHandler<int>(EventID.MODULE_DOWNLOAD_ERROR, this.DownError);
    }

    public void InitModuleState()
    {
        int errorId = PlayerPrefs.GetInt(DownloadingKeys, 0);
        foreach (MainItemInfo info in TableProtoLoader.MainItemInfoDict.Values)
        {
            int id = (int)info.id;
#if UNITY_IOS
            if (info.download_ios == 1)
            {
                ModuleAsset[id] = ModuleAssetState.NoDownload;

                if (AssetIsDownload(info.path) && id != errorId)
                {
                    ModuleAsset[id] = ModuleAssetState.Downloaded;
                    LoadResInfo(id);
                }
                versionCheck[id] = false;
            }
#else
            if (info.download == 1)
            {
                ModuleAsset[id] = ModuleAssetState.NoDownload;

                if (AssetIsDownload(info.path) && id != errorId)
                {
                    ModuleAsset[id] = ModuleAssetState.Downloaded;
                    LoadResInfo(id);
                }
                versionCheck[id] = false;
            }
#endif
            else
            {
                ModuleAsset[id] = ModuleAssetState.Downloaded;
            }
        }
        PlayerPrefs.DeleteKey(DownloadingKeys);
    }

    public ModuleAssetState GetAssetState(int id)
    {
        return ModuleAsset[id];
    }

	public bool AssetIsDownload(string name) {
		string resPath = FileTools.CombinePath (ResourceManager.PersistentAssetPath, name + ResourceManager.RES_INFO_NAME);
		return FileTools.IsFileExist (resPath);
	}

    public void VersionCheck(int id)
    {
        if (!versionCheck.ContainsKey(id))
        {
            return;
        }
        if (versionCheck[id])
        {
            return;
        }
        //检测版本
        MainItemInfo info = TableProtoLoader.MainItemInfoDict[(uint)id];
        if (AppVersion.ModuleVersion.ContainsKey(info.path))
        {
            Debug.LogError("check version " + id + "," + info.path + "," + AppVersion.ModuleVersion[info.path]);
            ModuleDownloadSystem.Instance.CheckUpdate(id, info.path, AppVersion.ModuleVersion[info.path], ()=> {
                ModuleAsset[id] = ModuleAssetState.NeedUpdate;
            });
        }
    }

    public void StartDownload(int id)
    {
        if (downloadQue.Contains(id))
        {
            Debug.Log("---------- ID重复");
            return;
        }
        MainItemInfo info = TableProtoLoader.MainItemInfoDict[(uint)id];
        Debug.Log("---------- 资源路径名: " + info.path);
        if (AppVersion.ModuleVersion.ContainsKey(info.path))
        {
            Debug.LogError(id + "," + info.path + "," + AppVersion.ModuleVersion[info.path]);
            ModuleAsset[id] = ModuleAssetState.Downloading;

            Debug.Log("---------- 当前资源下载数量: " + downloadQue.Count);
            if (downloadQue.Count == 0)
            {
                PlayerPrefs.SetInt(DownloadingKeys, id);
                ModuleDownloadSystem.Instance.StartDownload(id, info.path, AppVersion.ModuleVersion[info.path]);
            }
            downloadQue.Enqueue(id);
        }
    }

	public void UnZipModule(string name, Action<string> handler) {
		string assetPath = FileTools.CombinePath (Application.streamingAssetsPath, ResourceManager.ASSETPATH);
		//ModuleAsset [name].IsUnziping = true;
		this.UnzipDoneHander = handler;
		ModuleDownloadSystem.Instance.CopyZip (assetPath, name);
        //LoadResInfo(ModuleConst.MaerdaifuName);
    }

    private void DownError(int id)
    {
        ModuleAsset[id] = ModuleAssetState.NoDownload;
        PlayerPrefs.DeleteKey(DownloadingKeys);
        ContinusDown();
    }

    private void ContinusDown()
    {
        Debug.Log("---------- 检测队列数组！ QueueCount: " + downloadQue.Count);
        downloadQue.Dequeue();
        if (downloadQue.Count > 0)
        {
            int newid = downloadQue.Peek();
            MainItemInfo info = TableProtoLoader.MainItemInfoDict[(uint)newid];
            PlayerPrefs.SetInt(DownloadingKeys, newid);
            ModuleDownloadSystem.Instance.StartDownload(newid, info.path, AppVersion.ModuleVersion[info.path]);
        }
    }


    private void UnzipDone(int id, long allSize) {
        DownloadItemManager.Instance.AddDownload(id, allSize);
        PlayerPrefs.DeleteKey(DownloadingKeys);
        ModuleAsset[id] = ModuleAssetState.Downloaded;
        LoadResInfo(id);
        ContinusDown();
    }

	public void LoadResInfo(int id) {
        MainItemInfo infoItem = TableProtoLoader.MainItemInfoDict[(uint)id];
        string path = FileTools.CombinePath (ResourceManager.PersistentAssetPath, infoItem.path+ResName);
		if (FileTools.IsFileExist (path)) {
			string info = File.ReadAllText (path);
			ResourceManager.Instance.AddPackerInfoSet (info);
			//ModuleAsset [name].IsReadInfo = true;
		}
	}

    public void DeleteRes(int id)
    {
        ModuleAsset[id] = ModuleAssetState.NoDownload;
        MainItemInfo infoItem = TableProtoLoader.MainItemInfoDict[(uint)id];
        string path = FileTools.CombinePath(ResourceManager.PersistentAssetPath, infoItem.path + ResName);
        if (FileTools.IsFileExist(path))
        {
            string info = File.ReadAllText(path);
            ResourceInfo resInfo = JsonUtility.FromJson<ResourceInfo>(info);
            if (resInfo != null)
            {
                for (int i = 0; i < resInfo.ResList.Count; i++)
                {
                    FileTools.DeleteFile(FileTools.CombinePath(ResourceManager.PersistentAssetPath, resInfo.ResList[i].Name));
                }
            }
            FileTools.DeleteFile(path);
        }
    }
}
